package
{
	
	import api.dataStruct.BaseRecordVO;
	import api.dataStruct.BuyItemVO;
	import api.dataStruct.GameApiInfo;
	import api.dataStruct.GameInfo;
	import api.dataStruct.GetItemInfoVO;
	import api.dataStruct.InitAPIObj;
	import api.dataStruct.ReadStoreVO;
	import api.dataStruct.SaveStoreVO;
	import api.dataStruct.ServerStoreVO;
	import api.dataStruct.SetFaceVO;
	import api.dataStruct.SetStruct;
	import api.dataStruct.ShareWBVO;
	import api.dataStruct.ShowMouseObj;
	import api.dataStruct.UseItemVO;
	import api.event.CallFunName;
	import api.event.CustomEvent;
	import api.event.EventData;
	import api.event.EventSendObj;
	import api.event.GameAPIEvent;
	
	import com.adobe.serialization.json.JSON;
	import com.api.StaticData;
	import com.api.ui.API_UI;
	import com.api.vo.Config;
	import api.dataStruct.FaceDataObj;
	import com.api.vo.SendChatObj;
	import com.dynamicflash.util.Base64;
	import com.game.btnClass.AddMouseEvent;
	import com.game.utils.GlobalFun;
	import com.game.utils.LoadStrData;
	import com.game.utils.MyTimer;
	import com.game.utils.TestBtn;
	
	import dataStruct.UserBuffer;
	
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.ContextMenuEvent;
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.media.SoundChannel;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.system.System;
	import flash.text.TextField;
	import flash.ui.ContextMenu;
	import flash.ui.ContextMenuItem;
	import flash.utils.ByteArray;
	
	import mx.utils.StringUtil;
	
	import open3366.as3.Open3366Ad;
	import open3366.as3.Open3366Api;
	import open3366.as3.Open3366Core;
	import open3366.as3.Open3366Event;
	
	import open3366pvp.as3.Open3366PvpApi;
	import open3366pvp.as3.Open3366PvpConfig;
	import open3366pvp.as3.Open3366PvpEvent;
	import open3366pvp.as3.dataStruct.IPvpInfo;
	
	public class API_3366_AS3 extends Sprite
	{
		//显示对象
		public var debugTxt:TextField;
		
		private var _api_ui:API_UI
		private var _apiSP:Sprite
		
		
		//用户信息
		private var _uid:String;
		private var _nickName:String="player";
		private var _headPic:String;
		private var _timeStamp:uint=0;
		private var _accessToken:String;
		private var _gameId:uint;
		private var _zoneID:int=1;
		private var _roomID:int=-1;
		private var _tableID:int=-1;
		private var _myApiInfo:GameApiInfo;
		private var _otherApiInfo:GameApiInfo;;
		private var _userGameInfo:Object;
		
		//游戏信息
		
		private var _cVer:String="API版本:1.1";
		private var _actorList:Array;
		private var _gameInfo:GameInfo;
		private var _getUserListObj:Object;
		private var _userList:Vector.<GameApiInfo>=new Vector.<GameApiInfo>();
		private var _totalPlayers:uint;
		private var _totalUser:uint;
		private var _isMeHost:Boolean=false;
		private var _frameRate:uint;
		
		private var _verStr:String="";
		
		//提示信息
		private var _clew_1:String="如长时间无响应,请按F5刷新";
		private var _clew_2:String="把游戏地址发给好友一起玩吧";
		private var _clew_3:String="请按F5刷新"
		
		private var _apiType:uint=0;
		private var _isDebug:uint=0;
		private var _isChat:Boolean=false;
		private var _isAddListener:Boolean=false;
		private var _isChangePlayer:Boolean=false;
		private var _isStartGame:Boolean=false;
		private var _isRobot:Boolean=false;
		private var _isNeedRegPVP:Boolean=false;
		private var _isRegedPVP:Boolean=false;
		private var _isEnterTable:Boolean=false;
		private var _isEnterZone:Boolean=false;
		private var _isHttp:Boolean=false;
		
		
		private var _tryInitTimes:uint=0;
		private var _maxInitTimes:uint=20;
		private var _tryQuickTimes:uint=0;
		private var _maxQuickTimes:uint=20;
		
		private var _heartTime:uint;
		
		private var _heartTimer:MyTimer;
		
		
		/////////////////////////////////////
		private var _recordData:BaseRecordVO
		
		
		public function API_3366_AS3()
		{
			this.addEventListener(Event.ADDED_TO_STAGE,onStage)
			
		}
		private function onStage(e:Event):void{
			stage.scaleMode=StageScaleMode.NO_SCALE;
			stage.align=StageAlign.TOP_LEFT;
			this.removeEventListener(Event.ADDED_TO_STAGE,onStage);
			init();
		}
		
		/////////////////////////////////////////////////////////////////////
		//API调用Game方法
		
		//////////////////////////////////////////////////////////////////////
		private function debug(str:String):void{
			trace(str);
			debugTxt.appendText(str+"\n")
			if(_isDebug==0){
				return;
			}
			if(_isChat){
				_api_ui.chatMc.gameClew(str);
			}
			_api_ui.disDebugTxt(str);
		}
		/**
		 * @param _obj  聊天内容
		 * @param type 聊天类型,=0文字,=1表情
		 * 
		 * */
		private function sendChatObjFun(_obj:SendChatObj):void{
			sendToAPIFun("getChatMsg",0,_obj);
		}
		private function pauseGame(isPause:Boolean=true):void{
			apiCallGameFun(CallFunName.G_STOP_GAME,isPause);
		}
		private function getChatMsg(obj:Object=null):void{
			
			if(!_isChat){
				return;
			}
			var _sendChatObj:SendChatObj=new SendChatObj();
			GlobalFun.setObjData(_sendChatObj,obj,1);
			
			var _str:String="";
			var _faceName:String;
			var _userName:String=_otherApiInfo.nick;
			
			if(_sendChatObj.type==0){
				_str=_sendChatObj.obj
			}else if(_sendChatObj.type==1){
				var _faceDataObj:FaceDataObj=new FaceDataObj();
				GlobalFun.setObjData(_faceDataObj,_sendChatObj.obj,1)
				_faceName=_faceDataObj.desc;
				_api_ui.chatMc.showFace(_faceDataObj.fName,false);
			}
			_api_ui.chatMc.addChatList(_str,_faceName,_userName);
		}
		
		
		
		private function getTableUsers(data:*=null):void
		{
			//获取制定桌子所有用户
			
			if(!_isRobot&&_isStartGame){
				return;
			}
			if(_isRobot){
				_isRobot=false;
				_isStartGame=false;
				_api_ui.disUserLeave(function ():void{restart(true)});
				pauseGame(true);
				clearRobot();
				return;
			}
			_api_ui.delUserLeave();
			Open3366PvpApi.getUserList(_roomID, _tableID);
			_api_ui.delMatchPlayer();
			_api_ui.disInitClew("正在获取玩家");
		}
		
		
		
		private function onGetUsersList(Obj:Object):void
		{
			_userList=null;
			_userList=new Vector.<GameApiInfo>();
			
			var _tempUserList:Array=Obj.userList;
			
			_totalUser=_tempUserList.length;
			
			if(_totalUser>_totalPlayers){
				_api_ui.disInitClew("玩家数超标");
				return;
			}
			if(_isChat){
				_api_ui.chatMc.delUserHead();
			}
			for(var i:int=0;i<_totalUser;i++){
				if(_tempUserList[i].uid!=_uid){
					var _userBuffer:UserBuffer=new UserBuffer();
					_otherApiInfo=new GameApiInfo();
					SetStruct.setObjData(_userBuffer,JSON.decode(_tempUserList[i].bufferData));
					_otherApiInfo.nick=_tempUserList[i].nick;
					_otherApiInfo.uid=_tempUserList[i].uid;
					_otherApiInfo.isHost=_userBuffer.isHost;
					_otherApiInfo.actorName=_userBuffer.actorName;
					_otherApiInfo.headPic=_userBuffer.headPic;
					apiCallGameFun(CallFunName.G_SET_USER_INFO,_otherApiInfo);
					_userList.push(_otherApiInfo);
					if(_isChat){
						_api_ui.chatMc.addUserHead(_otherApiInfo,false);
					}
				}
			}
			if(_myApiInfo==null||!_myApiInfo.isBuffer){
				
				if (_totalUser==1) 
				{
					_isMeHost=true;
					
				}else {
					_isMeHost=false;
				}	
				_myApiInfo=new GameApiInfo(_uid,_nickName,_isMeHost,getActorName(getActorList()),1,_zoneID,_roomID,_tableID);
				_myApiInfo.timeStamp=_timeStamp;
				apiCallGameFun(CallFunName.G_SET_MY_INFO,_myApiInfo);
				saveMyBuffer(_myApiInfo);
			}
			if(_isChat){
				_api_ui.chatMc.addUserHead(_myApiInfo);
			}
			_userList.push(_myApiInfo);
			
			if(_isMeHost&&_totalUser==_gameInfo.totalPlayers&&!_isStartGame){
				sendToAPIFun("getStartGame",1);
			}else{
				_api_ui.delInitClew();
				_api_ui.disMatchPlayer(initRobot);
			}
		}
		
		
		private function getStartGame(Obj:*=null):void{
			_api_ui.delMatchPlayer();
			_api_ui.delAllAlert();
			_isStartGame=true;
			apiCallGameFun(CallFunName.G_START_GAME);
		}
		private function initRobot():void{
			_isRobot=true;
			_isStartGame=true;
			_api_ui.delMatchPlayer();
			_otherApiInfo=getRobotInfo();
			apiCallGameFun(CallFunName.G_SET_USER_INFO,_otherApiInfo);
			_userList.push(_otherApiInfo);
			if(_isChat){
				_api_ui.chatMc.addUserHead(_otherApiInfo,false);
			}
			apiCallGameFun(CallFunName.G_START_GAME,true);
			_heartTimer=new MyTimer();
			_heartTimer.setTimer(sendHeartData,_heartTime);
		}
		private function clearRobot():void{
			_isRobot=false;
			_isStartGame=false;
			if(_heartTimer!=null){
				_heartTimer.gc();
			}
			_heartTimer=null;
		}
		private function sendHeartData():void{
			sendToAPIFun("recHeart",1);
		}
		private function recHeart(data:*=null):void{
			
		}
		
		private function saveMyBuffer(gameApiInfo:GameApiInfo):void{
			
			if(gameApiInfo.isBuffer){
				return;
			}
			
			var _myBuffer:UserBuffer=new UserBuffer();
			_myBuffer.isHost=gameApiInfo.isHost;
			_myBuffer.actorName=gameApiInfo.actorName;
			gameApiInfo.headPic=_myBuffer.headPic=_headPic;
			gameApiInfo.isBuffer=true;
			setUserInfo(_nickName,JSON.encode(_myBuffer));
		}
		
		private function setUserInfo(nick:String,prop:String=""):void
		{
			nick = StringUtil.trim(nick);
			prop = StringUtil.trim(prop);
			var by:ByteArray = new ByteArray();
			var strLen:int = getStrCount_pvp(prop);
			by.writeBytes(writeStr_pvp(prop, strLen));
			Open3366PvpApi.setUserProp(nick, by);
			_api_ui.disInitClew("设置用户属性");
		}
		private function initTestUserInfo():void{
			_isRobot=true;
			_isStartGame=true;
			_myApiInfo=getRobotInfo();
			_myApiInfo.isHost=true;
			apiCallGameFun(CallFunName.G_SET_MY_INFO,_myApiInfo);
			_otherApiInfo=getRobotInfo();
			apiCallGameFun(CallFunName.G_SET_USER_INFO,_otherApiInfo);
		}
		
		private function restart(isAdd:Boolean):void{
			_isStartGame=false;
			pauseGame(false);
			apiCallGameFun(CallFunName.G_USER_CHANGE,isAdd);
			_api_ui.delUserLeave();
			_api_ui.delAllAlert();
		}
		//++++++++++++++++++++++++++++++++++++++++++++++++++++++
		//Game_A调用API_A
		
		private function setFaceList(vo:SetFaceVO):void{
			if(vo.isShow){
				_api_ui.disFaceList(vo.point,vo.callBack);
			}else{
				_api_ui.delFaceList();
			}
			vo=null;
		}
		
		private function setGameStae(data:Boolean):void{
			_isStartGame=data;
		}
		private function initAPI(data:InitAPIObj):void
		{
			_gameInfo=data.gameInfo;
			_totalPlayers=_gameInfo.totalPlayers
			_actorList=_gameInfo.actorList.concat();
			StaticData.gameW=_gameInfo.gameW;
			StaticData.gameH=_gameInfo.gameH;
			StaticData.gameId=_gameInfo.gameId;
			StaticData.isChat=_isChat=data.isChat
			_frameRate=data.gameInfo.frameRate;
			_gameId=data.gameInfo.gameId;
			_apiType=data.type;
			_isDebug=data.isDebug;
			_headPic=getHeadPic();
			_api_ui.isChat=_isChat;
			
			if(_isChat){
				StaticData.chatHeight=110;
				_api_ui.initChat(sendChatObjFun);
				
			}else{
				StaticData.chatHeight=0;
			}
			new  LoadStrData("resource/config.txt"+_verStr,loadConfigCom);
			this.setChildIndex(debugTxt,this.numChildren-1);
		}
		private function gameOver(data:*):void{
			trace("游戏结束");
		}
		private function gameStart(data:*):void{
			trace("游戏开始");
		}
		private function isDisRecommandBtn(data:*):void{
			_api_ui.isDisRecommendBtn(data);
		}
		private function showRecommend(data:*):void{
			_api_ui.disRecommend();
		}
		private function isTurnMe(data:*):void{
			
			_api_ui.isDisTurnMe(data);
			
		}
		//分享到微博
		private function shareWB(data:*):void{
			
			var _data:ShareWBVO=data as ShareWBVO;
			Open3366Api.addEventListener(Open3366Event.SEND_WEIBO, onSendWeibo);  
			Open3366Api.sendWeibo(_data.content,_data.picUrl); 
			debug("调用发布到微博接口:"+_data.toString());
			function onSendWeibo(e:Open3366Event):void{
				var data:Object = e.data;
				debug("布到微博接口返回:"+e.toString());
				if(_data.callBack!=null){
					_data.callBack(data.result);
				}
				if(data.result == 0)
				{
					//成功
					debug("微博发布成功");
				}else{
					//失败
				}
			}
		}
		
		private function disWaitData(data:*):void{
			_api_ui.disWaitData(data);
		}
		private function delWaitData(data:*):void{
			_api_ui.delWaitData();
		}
		private function askAgain(data:*):void{
			_api_ui.delAllAlert();
			if(_apiType==InitAPIObj.TYPE_1||_apiType==InitAPIObj.TYPE_2){
				_api_ui.disInitClew("等待对方回应");
				sendToAPIFun("disAgain");
			}else if(_apiType==InitAPIObj.TYPE_5||_apiType==InitAPIObj.TYPE_6){
				sendToAPIFun("wantAgain");
			}
		}
		
		private function wantAgain(Obj:*=null):void{
			apiCallGameFun(CallFunName.G_WANT_AGAIN);
		}
		
		private function buyItim(data:*):void{
			var _vo:BuyItemVO=data as BuyItemVO;
			debug(_vo.toString());
			Open3366Api.addEventListener(Open3366Event.SHOP_BACK,onShopBack);
			Open3366Api.buyItem(_vo.itemId,_vo.count,_vo.roleId);
			
			function onShopBack (e:Open3366Event):void
			{
				var data:Object = e.data;
				if(_vo.callBack!=null){
					_vo.callBack(data.result,_vo);
					_vo.callBack=null;
				}
				_vo=null;
				if(data.result == 0){
					debug("购买成功")
				}else
				{
					debug("购买面板被关闭")
				}
				//{"result":0}
				//result = 0表示购买成功
				//result = 1,表示购买面板被关闭
			} 
		}
		private function getOneItim(data:*):void{
			var _vo:GetItemInfoVO=data as GetItemInfoVO;
			debug(_vo.toString());
			Open3366Api.addEventListener(Open3366Event.ITEM_DETAIL, onGetItem);
			Open3366Api.getItem(_vo.itemId,_vo.roleId);
			function onGetItem (evt:Open3366Event):void
			{
				var data:Object = evt.data;//（json数据格式）
				if(_vo.callBack!=null){
					_vo.callBack(data);
					_vo.callBack=null;
				}
				_vo=null;
				if(data.result == 0){
					debug("购买成功")
				}else
				{
					debug("购买面板被关闭")
				}
			}
		}
		private function useItim(data:*):void{
			var _vo:UseItemVO=data as UseItemVO;
			debug(_vo.toString());
			Open3366Api.addEventListener(Open3366Event.CONSUME_ITEM, onConsumeItem);
			Open3366Api.consumeItem (_vo.itemId,_vo.count,_vo.roleId);
			function onConsumeItem (evt:Open3366Event):void
			{
				var data:Object = evt.data;//（json数据格式）
				if(_vo.callBack!=null){
					_vo.callBack(data,_vo);
					_vo.callBack=null;
				}
				_vo=null
			}
			
		}
		private function getAllItim(data:*):void{
			
		}
		
		/**
		 * 保存记录
		 * @param data:SetStoreVO
		 */
		private function saveStore(data:*):void{
			var _setStoreData:SaveStoreVO=data as SaveStoreVO;
			
			debug("保存数据:"+JSON.encode(_setStoreData.data));
			
			Open3366Api.addEventListener(Open3366Event.STORE_SET,setStoreOver)
			Open3366Api.setData(_setStoreData.title,_setStoreData.data,_setStoreData.index,_setStoreData.pageId);
			if(_setStoreData.clewStr!=null){
				_api_ui.disInitClew(_setStoreData.clewStr);
			}
			
			function setStoreOver(e:Open3366Event):void{
				var data:Object = e.data;
				onSetStore(data);
				if(_setStoreData.callBack!=null){
					_setStoreData.callBack(data.result);
					_setStoreData.callBack=null;
				}
				_setStoreData=null;
				Open3366Api.removeEventListener(Open3366Event.STORE_SET,setStoreOver);
				_api_ui.delInitClew();
			}
			//			debug("setStore:"+_setStoreData.toString());
		}
		/**
		 * 读取记录
		 * @param data:GetStoreVO
		 */
		private function readStore(data:*):void{
			var _getStoreData:ReadStoreVO=data as ReadStoreVO;
			Open3366Api.addEventListener(Open3366Event.STORE_GET,readStoreOver);
			Open3366Api.getData(_getStoreData.index,_getStoreData.pageId);
			if(_getStoreData.clewStr!=null){
				_api_ui.disInitClew(_getStoreData.clewStr);
			}
			function readStoreOver(e:Open3366Event):void{
				var data:Object = e.data;
				var storeVO:ServerStoreVO=new ServerStoreVO();
				
				debug("读档数据:"+JSON.encode(data));
				
				GlobalFun.setObjData(storeVO,data,1);
				
				onGetStore(storeVO);
				
				if(_getStoreData.callBack!=null){
					_getStoreData.callBack(storeVO);
					_getStoreData.callBack=null;
				}
				_getStoreData=null;
				Open3366Api.removeEventListener(Open3366Event.STORE_GET,readStoreOver);
				_api_ui.delInitClew();
			}
			//			debug("getStore:"+_getStoreData.toString());
		}
		private function setRecord(score:uint=0):void{
			
			if(_recordData==null){
				return;
			}
			if(_recordData.maxScore==-1){
				_recordData.maxScore=score;
			}
			if(_recordData.minScore==-1){
				_recordData.minScore=score;
			}
			if(score>_recordData.maxScore){
				_recordData.maxScore=score;
				
			}else if(score<_recordData.minScore){
				_recordData.minScore=score
			}
			var _total:uint=(_recordData.meanScore*_recordData.times)+score;
			_recordData.times++;
			_recordData.meanScore=Math.floor(_total/_recordData.times);
			
			saveStore(new SaveStoreVO("游戏统计",_recordData,1,1));
		}
		
		private function apiAlert(str:String):void{
			_api_ui.disAlert(str);
		}
		private function disInitClew(str:String):void{
			trace("disInitClew");
			_api_ui.disInitClew(str);
		}
		private function delAllAlert(data:*=null):void{
			_api_ui.delAllAlert();
		}
		
		//===============================================
		//发布到微博回调
		private function onGetBaseRecord( getStoreVO:ServerStoreVO):void{
			if(getStoreVO.index==1){
				_recordData=new BaseRecordVO(); 
				if(getStoreVO.data.times!="undefined"){
					GlobalFun.setObjData(_recordData,getStoreVO.data);
					debug(_recordData.toString());
				}
			}
		}
		private function onSetStore(data:Object):void{
			
			
			if(data.result == 0)
			{
				debug("存档成功");
			}else if(data.result == 10002)
			{
				debug("用户未登录。请调用showLogin先登录");
			}else
			{
				debug("请求失败");
			}
		}
		private function onGetStore(storeVO:ServerStoreVO):void{
			
			
			
			
			
			if(storeVO.result == 0)
			{
				debug("读档成功。 index ="+storeVO.index+",title="+ storeVO.title+", data="+ storeVO.data+", time="+storeVO.time);
				
			}else if(storeVO.result == 10002)
			{
				debug("用户未登录。请调用showLogin先登录");
			}else
			{
				debug("请求失败");
			}
		}
		
		
		
		private function loadConfigCom(str:String):void{
			var _config:Config=new Config();
			var _data:Object=(JSON.decode(str) as Object).data;
			GlobalFun.setObjData(_config,_data);
			StaticData.config=_config;
			_heartTime=_config.heartTime;
			setRightMenu();
			
			switch(_apiType){
				case InitAPIObj.TYPE_1:
					_isNeedRegPVP=true;
					registerAPI();
					break
				case InitAPIObj.TYPE_2:
					_isNeedRegPVP=true
					initMyAPIInfo();
					break
				case InitAPIObj.TYPE_5:
					_isNeedRegPVP=false;
					registerAPI();
					break
				case InitAPIObj.TYPE_6:
					_isNeedRegPVP=false;
					initMyAPIInfo()
					break
				case InitAPIObj.TYPE_10:
					_api_ui.delAllAlert();
					_api_ui.disStartGame(startTestGame);
					break
				default:
					
			}
		}
		private function initMyAPIInfo():void{
			_api_ui.delAllAlert();
			_myApiInfo=getRobotInfo();
			apiCallGameFun(CallFunName.G_INIT_API_COM,_myApiInfo);
		}
		private function setInitPVP(data:*):void{
			trace("setInitPVP:"+_isRegedPVP,_isEnterZone,_isEnterTable);
			if(_isRegedPVP){
				//已经注册了PVP
				if(_isEnterTable){
					getTableUsers();
				}else{
					onInitOver_PVP();
				}
				
			}else{
				//没有注册pvp
				if(_apiType==InitAPIObj.TYPE_2||_apiType==InitAPIObj.TYPE_6){
					regPVPDeubg();
				}else if(_apiType==InitAPIObj.TYPE_5){
					initPVP();
				}
			}
		}
		private function regPVPDeubg():void{
			_api_ui.delAllAlert();
			_api_ui.disChooseUser(chooseUser);
			StaticData.config.matchTime=5;
		}
		
		private function startTestGame():void{
			initTestUserInfo();
			apiCallGameFun(CallFunName.G_START_GAME,true);
			_api_ui.delStartGame();
		}
		
		private function disAgain(Obj:*=null):void{
			_api_ui.disAgain(acceptAgain,changePlayer);
		}
		private function acceptAgain(data:*=null):void{
			sendToAPIFun("getAgain",1);
		}
		private function getAgain(Obj:*=null):void{
			_api_ui.delAgain();
			_api_ui.delAllAlert();
			apiCallGameFun(CallFunName.G_AGAIN);
		}
		private function quitRoom(data:*=null):void{
			if(!_isEnterZone){
				return;
			}
			Open3366PvpApi.quitZone();
			_isEnterZone=_isEnterTable=false;
			_isRobot=false;
			_isStartGame=false;
			clearRobot();
		}
		////////////////////////////////////////////////////////////////
		
		
		private function changePlayer(data:*=null):void{
			_api_ui.delAgain();
			_api_ui.delAllAlert();
			_isChangePlayer=true;
			//退出桌子
			Open3366PvpApi.quitTable();
			_api_ui.disInitClew("正在退出桌子");
		}
		
		
		private function chooseUser(str:String):void{
			if (str=="A") 
			{
				_nickName+="aaa";
				setChooseUserInfo("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",0,"6884ed4da9e9de77879724054f7f5b01",8);
			}else if(str=="B"){
				_nickName+="bbb";
				setChooseUserInfo("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",0,"85f1600aa14e398169a71643d9f2aa88",8);
			}
			_api_ui.delChooseUser();
			initPVP();
		}
		private function setChooseUserInfo(szUID:String,uiTimeStamp:uint,szAccessToken:String, uiGameID:uint):void{
			
			_uid=szUID;
			_timeStamp=uiTimeStamp;
			_accessToken=szAccessToken;
			_gameId=uiGameID;
			_zoneID=StaticData.config.zoneID;
			_roomID=StaticData.config.roomID;  
			_tableID=StaticData.config.tableID;
			
		}
		
		
		
		////////////////////////////////////////////////////
		//初始化PVP    注册PVP/		添加监听事件
		
		private function initPVP():void{
			if(_isRegedPVP){
				
				return;
			}
			
			addListener_pvp();
			debug("initPVP _uid:"+_uid+" _timeStamp:"+_timeStamp+" _accessToken:"+_accessToken+" _gameId:"+_gameId+" this:"+this);
			Open3366PvpApi.initGame(_uid, _timeStamp, _accessToken, _gameId,this);
			
			_api_ui.disInitClew("初始化PVP组件",_clew_1);
		}
		
		//pvp组件注册完成
		private function onInitOver_PVP(evt:Open3366PvpEvent=null):void
		{
			debug("onInitOver_PVP"+_zoneID+" "+ _roomID+ " "+_tableID+" _isRegedPVP:"+_isRegedPVP+" _isEnterZone:"+_isEnterZone);
			_isRegedPVP=true;
			if(!_isEnterZone){
				//快速开始游戏
				Open3366PvpApi.quickEnterGame( _zoneID, _roomID, _tableID);
			}else{
				quitEnterTable();
			}
			
			_api_ui.disInitClew("正在加入桌子",_clew_1);
		}
		private function quitEnterTable():void{
			//快速加入桌子
			trace("quitEnterTable");
			_api_ui.disInitClew("正在加入桌子",_clew_1);
			Open3366PvpApi.quickEnterTable(-1, -1);
		}
		
		/**
		 * 成功退出桌子
		 */
		private function onQuitTable():void{
			_isEnterTable=false;
			if(_isChangePlayer){
				_isRobot=false;
				_isStartGame=false;
				_tableID=-1;
				_myApiInfo=null;
				_isChangePlayer=false;
				apiCallGameFun(CallFunName.G_INIT_PVP);
				_api_ui.delAllAlert();
			}
		}
		
		
		///////////////////////////////
		//初始化API组件
		private function init():void{
			_isHttp=GlobalFun.CheckHttp(this .stage.loaderInfo.url);
			if(_isHttp){
				_verStr="?v="+Math.random();
			}
			_api_ui=new API_UI(this);
			this.addEventListener(GameAPIEvent.PVP_GAME_TO_API,onGameEvent);
		}
		private function onGameEvent(e:CustomEvent):void{
			var _fun:String=e.data.type;
			if(!_fun){
				debug("myEvent.data.type不能为空!!!");
				return
			}
			var data:*=e.data.data;
			this[_fun](data);
		}
		private function callGameFun(eventType:String,data:EventData=null):void{
			this.dispatchEvent(new CustomEvent(GameAPIEvent.PVP_API_TO_GAME,new EventData(eventType,data)));
		}
		//API_A调用Game_A的方法
		private function apiCallGameFun(type:String,data:*=null):void{
			callGameFun("onAPICallFun",new EventData(type,data));
		}
		private function apiSetGamePropertry(type:String,data:*=null):void{
			callGameFun("onAPISetProperty",new EventData(type,data));
		}
		
		
		private function gameSendToTable(data:EventSendObj=null):void{
			sendMsgToTable_pvp(data);
		}
		
		private function sendToAPIFun(_eventType:String,_isToMe:uint=0,_data:*=null):void{
			sendMsgToTable_pvp(new EventSendObj(GameAPIEvent.PVP_MSG_API_FUN,_isToMe,new EventData(_eventType,_data)));
		}
		private function sendMsgToTable_pvp(eventSendObj:EventSendObj):void
		{
			if(!_isRegedPVP){
				return;
			}
			var sendContent:String=JSON.encode(new EventData(eventSendObj.eventType,eventSendObj.data));
			var by:ByteArray = new ByteArray();
			var strLen:int = getStrCount_pvp(sendContent);
			by.writeBytes(writeStr_pvp(sendContent, strLen));
			Open3366PvpApi.sendMsgToTable( by,_roomID, _tableID, eventSendObj.isToMe);
			by.position=0;
			//			trace("调用sendMsgToTable_pvp,content:"+sendContent+" str长度:"+sendContent.length+" by长度:"+by.length+" by.bytesAvailable:"+by.bytesAvailable)
		}
		
		private function getActorList():Array{
			var _arr:Array=[];
			for(var i:uint=0;i<_userList.length;i++){
				
				_arr.push(_userList[i].actorName);
			}
			return _arr;
		}
		private function getActorName(_arr:Array=null):String{
			if(_actorList==null){
				
				return "";
			}
			if(_actorList.length==0){
				return "";
			}
			if(_arr==null||_arr.length==0){
				return _actorList[0];
			}
			for(var i:uint=0;i<_actorList.length;i++){
				for(var n:uint=0;n<_arr.length;n++){
					if(_actorList[i]!=_arr[n]){
						return _actorList[i];
					}
				}
			}
			return "";
		}
		
		private function getRobotInfo():GameApiInfo{
			var _userInfo:GameApiInfo=new GameApiInfo();
			
			_userInfo.nick=GlobalFun.getRanArr(StaticData.config.robotNameList);
			_userInfo.uid="0";
			_userInfo.isHost=false;
			_userInfo.actorName=getActorName(getActorList());
			_userInfo.headPic=getHeadPic();
			_userInfo.timeStamp=_timeStamp;
			
			return _userInfo;
		}
		private function getHeadPic():String{
			return (Math.random()*7>>0)+1+"";
		}
		private function setRightMenu():void{
			var myContextMenu:ContextMenu = new ContextMenu();
			var more:ContextMenuItem = new ContextMenuItem(_cVer+"_"+StaticData.config.dVer,true,false);
			//			var _debug:ContextMenuItem=new ContextMenuItem("debug",true);
			//			_debug.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, debugFun);
			myContextMenu.customItems.push(more);
			myContextMenu.hideBuiltInItems();
			this.contextMenu = myContextMenu;
		}
		
		private function debugFun(e:ContextMenuEvent):void
		{
			
		}
		
		
		
		
		
		
		
		///////////////////////////////////////////////////////////////
		//=================================================================
		//初始化API
		private function registerAPI():void{
			Open3366Api.addEventListener(Open3366Event.SERVICE_READY, onServiceReady);
			Open3366Api.initGame(String(_gameId), this, true);	
			_api_ui.disInitClew("初始化组件",_clew_1);
			debug("开始初始化1.4.1的open3366API");
		}
		
		private function onServiceReady(evt:Open3366Event):void
		{
			Open3366Api.removeEventListener(Open3366Event.SERVICE_READY, onServiceReady);
			getUid();
			debug("初始化1.4.1的open3366API完成，开始获取uid");
		}
		
		private function getUid():void
		{
			Open3366Api.addEventListener(Open3366Event.CHECK_LOGIN,onCheckLogin);
			Open3366Api.isLogin();
			_api_ui.disInitClew("正在检测登录");
		}
		
		private function onCheckLogin(evt:Open3366Event):void
		{
			Open3366Api.removeEventListener(Open3366Event.CHECK_LOGIN,onCheckLogin);
			
			var retObj:Object = evt.data;
			var iRet:int = parseInt(retObj.result);
			var iLogin:int = parseInt(retObj.isLogin);
			
			if ((iRet == 0) || (iRet == 10002)) 
			{
				if (iLogin == 1)
				{
					_uid = retObj.uid;
					_nickName=retObj.nick;
					Open3366Api.removeEventListener(Open3366Event.SEND_MSG_TO_FLASH, onLogin);
					getToken();
					debug("获取uid成功，uid=" + _uid + "， 开始获取token和timeStamp");
				}
				else
				{
					Open3366Api.addEventListener(Open3366Event.SEND_MSG_TO_FLASH, onLogin);
					Open3366Api.showLogin();
					debug("用户未登录，弹出登录框");
				}
			}
			else 
			{
				_api_ui.disAlert("查询用户uid请求失败即isLogin()请求失败,请刷新重试");
				debug("查询用户uid请求失败即isLogin()请求失败");
			}
		}
		private function onLogin(evt:Open3366Event):void
		{
			//			Open3366Api.removeEventListener(Open3366Event.SEND_MSG_TO_FLASH, onLogin);
			var retObj:Object = evt.data;
			var iRet:int = parseInt(retObj.result);
			if (iRet == 0)
			{
				_api_ui.delAllAlert();
				debug("登录成功，开始获取uid");
				getUid();
			}
			else
			{
				_api_ui.disAlert("登录框被关闭,登录失败.请重新登录",getUid);
				debug("登录框被关闭，登录失败");
			}
			
		}
		private function getToken():void
		{
			_api_ui.disInitClew("正在获取Token");
			Open3366Api.addEventListener(Open3366Event.ACCESS_TOKEN,onGetToken);
			Open3366Api.getToken();
		}
		private function onGetToken(evt:Open3366Event):void
		{
			Open3366Api.removeEventListener(Open3366Event.ACCESS_TOKEN,onGetToken);
			var retObj:Object = evt.data;
			var iRet:int = parseInt(retObj.result);
			if (iRet == 0)
			{
				_accessToken = retObj.access_token;
				_timeStamp = retObj.timestamp;
				debug("获取token和timeStamp成功 。 token=" + _accessToken + ", timeStamp =" + _timeStamp +　"开始加载pvp组件");
				
				//				getStore(new R_getStore(1,1,onGetBaseRecord));//获取玩家游戏次数.分数,等基本数据
				_myApiInfo=new GameApiInfo(_uid,_nickName);
				_myApiInfo.timeStamp=_timeStamp;
				apiCallGameFun(CallFunName.G_INIT_API_COM,_myApiInfo);
				_api_ui.delAllAlert();
			}
			else
			{
				_api_ui.disAlert("请求token和timeStamp失败，即执行getToken失败");
				debug("请求token和timeStamp失败，即执行getToken失败");
			}
		}
		
		private function onPVPReceiveMsg(data:Object):void
		{
			//查看结构3366API-ServerMsg
			//msgFlag:int;//0，服务器转发的消息来自用户 1，退出桌子的通知消息 2，被别人踢下线时的通知 3,用户下线通知，即用户退出区通知
			if(data.msgFlag!=0){
				//1:其他用户已经离线
				
				if(_isChat){
					_api_ui.chatMc.delUserHead();
				}
				
				
				_myApiInfo.isHost=_isMeHost=true;
				_myApiInfo.isBuffer=false;
				
				if(_isStartGame){
					saveMyBuffer(_myApiInfo);
					_myApiInfo.isBuffer=false;
					pauseGame(true);
					_api_ui.disUserLeave(function ():void{restart(false)});
				}else{
					apiCallGameFun(CallFunName.G_USER_CHANGE,false);
					quitRoom();
				}
				
				return;
			}
			var _dataStr:String=data.content;
			if (_dataStr.length==0||!_dataStr) 
			{
				return	;
			}
			var _dataObj:Object=JSON.decode(_dataStr);
			switch(_dataObj.type)
			{
				
				case GameAPIEvent.PVP_MSG_API_FUN:
				{
					this[_dataObj.data.type](_dataObj.data.data);
					break;
				}
				default:
				{
					var _eventData:EventData=new EventData(_dataObj.data.type,_dataObj.data.data);
					callGameFun(_dataObj.type,_eventData);
					break;
				}
			}
		}
		private function onSocketClose_pvp(evt:Open3366PvpEvent):void
		{
			_api_ui.disAlert("socket关闭连接,"+_clew_3);
			debug("socket关闭连接");
			callGameFun(GameAPIEvent.PVP_CLOSE);
		}
		
		private function onSocketError_pvp(evt:Open3366PvpEvent):void
		{
			_api_ui.disAlert("socket出现I/O错误或者安全沙箱错误,"+_clew_3);
			debug("socket出现I/O错误或者安全沙箱错误")
			callGameFun(GameAPIEvent.PVP_ERROR);
		}
		private function onSocketData_pvp(evt:Open3366PvpEvent):void
		{
			var data:IPvpInfo = evt.data.info;
			var iRet:int = evt.data.iRet;
			if(iRet == 0)
			{
				debug("data.toString"+data.toString()+",type:"+evt.type);
			}else
			{
				debug("socket出现逻辑错误或者系统错误： 错误码:" + evt.data.iRet + "\n 错误描述：" + Open3366PvpConfig.getErrorDes(evt.data.iRet)+"\ndata:"+data.toString());
			}
			switch(evt.type){
				case Open3366PvpEvent.RE_CONNECT_SUCCESS:
					break
				case Open3366PvpEvent.QUICK_ENTER_GAME:
					_isEnterZone=true;
					_zoneID=data["zoneId"];
					_roomID=data["roomId"];
					_tableID=data["tableId"];
					if(_zoneID!=0&&_roomID!=0&&_tableID!=0){
						_isEnterTable=true;
						Open3366PvpApi.getTableList(_roomID);
						Open3366PvpApi.getRoomList();
						
						getTableUsers();
						
					}else{
						//						onInitOver_PVP();
					}
					break;
				case Open3366PvpEvent.GET_USER_LIST:
					onGetUsersList(data);
					break;
				case Open3366PvpEvent.SERVER_MESSAGE:
					onPVPReceiveMsg(data)
					break;
				case Open3366PvpEvent.SET_USER_PROP:
					sendToAPIFun("getTableUsers");
					break;
				case Open3366PvpEvent.ENTER_ROOM:
					break;
				case Open3366PvpEvent.ENTER_TABLE:
					
					break;
				case Open3366PvpEvent.QUIT_TABLE:
					onQuitTable();
					break;
				case Open3366PvpEvent.QUIT_ROOM:
					break
				case Open3366PvpEvent.QUIT_ZONE:
					break;
			}
		}
		private function addListener_pvp():void{
			if(!_isAddListener){
				_isAddListener=true;
			}else{
				return;
			}
			Open3366PvpApi.addEventListener(Open3366PvpEvent.INIT_GAME_OVER, onInitOver_PVP);
			Open3366PvpApi.addEventListener(Open3366PvpEvent.SOCKET_CLOSE, onSocketClose_pvp);
			Open3366PvpApi.addEventListener(Open3366PvpEvent.SOCKET_ERROR, onSocketError_pvp);
			
			Open3366PvpApi.addEventListener(Open3366PvpEvent.QUICK_ENTER_GAME, onSocketData_pvp);
			
			Open3366PvpApi.addEventListener(Open3366PvpEvent.ENTER_ZONE, onSocketData_pvp);
			Open3366PvpApi.addEventListener(Open3366PvpEvent.ENTER_ROOM, onSocketData_pvp);
			Open3366PvpApi.addEventListener(Open3366PvpEvent.ENTER_TABLE, onSocketData_pvp);
			
			Open3366PvpApi.addEventListener(Open3366PvpEvent.GET_ZONE_LIST, onSocketData_pvp);
			
			Open3366PvpApi.addEventListener(Open3366PvpEvent.GET_ROOM_LIST, onSocketData_pvp);
			Open3366PvpApi.addEventListener(Open3366PvpEvent.GET_ROOM_INFO, onSocketData_pvp);
			Open3366PvpApi.addEventListener(Open3366PvpEvent.GET_MASS_ROOM_INFO, onSocketData_pvp);
			
			Open3366PvpApi.addEventListener(Open3366PvpEvent.GET_TABLE_LIST, onSocketData_pvp);
			Open3366PvpApi.addEventListener(Open3366PvpEvent.GET_TABLE_INFO, onSocketData_pvp);
			Open3366PvpApi.addEventListener(Open3366PvpEvent.GET_MASS_TABLE_INFO, onSocketData_pvp);
			
			Open3366PvpApi.addEventListener(Open3366PvpEvent.GET_USER_LIST, onSocketData_pvp);
			Open3366PvpApi.addEventListener(Open3366PvpEvent.GET_USER_INFO, onSocketData_pvp);
			Open3366PvpApi.addEventListener(Open3366PvpEvent.GET_MASS_USER_INFO, onSocketData_pvp);
			
			Open3366PvpApi.addEventListener(Open3366PvpEvent.SET_ZONE_PROP, onSocketData_pvp);
			Open3366PvpApi.addEventListener(Open3366PvpEvent.CREATE_AND_SET_ROOM_PROP, onSocketData_pvp);
			Open3366PvpApi.addEventListener(Open3366PvpEvent.CREATE_AND_SET_TABLE_PROP, onSocketData_pvp);
			Open3366PvpApi.addEventListener(Open3366PvpEvent.SET_USER_PROP, onSocketData_pvp);
			
			Open3366PvpApi.addEventListener(Open3366PvpEvent.SERVER_MESSAGE, onSocketData_pvp);
			
			Open3366PvpApi.addEventListener(Open3366PvpEvent.QUIT_TABLE, onSocketData_pvp);
			Open3366PvpApi.addEventListener(Open3366PvpEvent.QUIT_ROOM, onSocketData_pvp);
			Open3366PvpApi.addEventListener(Open3366PvpEvent.QUIT_ZONE, onSocketData_pvp);
			
			Open3366PvpApi.addEventListener(Open3366PvpEvent.SET_GAME_PROP_SUCCESS, onSocketData_pvp);
			
			Open3366PvpApi.addEventListener(Open3366PvpEvent.GET_ZONE_INFO, onSocketData_pvp);
			
			Open3366PvpApi.addEventListener(Open3366PvpEvent.RE_CONNECT_SUCCESS, onSocketData_pvp);
		}
		private function getStrCount_pvp(str:String):int
		{
			var strByte:ByteArray = new ByteArray();
			strByte.writeMultiByte(str, "utf-8");
			return strByte.length;
		}
		private function writeStr_pvp(str:String, len:int):ByteArray
		{
			var byte:ByteArray = new ByteArray();
			byte.writeUTFBytes(str);
			byte.length = len;
			return byte;
		}
	}
}